/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

import { downloadArrayBufferFile, encryptSign, getMd5, getToken } from '@/utils/utils'
import { fingerprintFetch, requestBuffer } from '@/utils/request';
import { RequestOptionsInit } from 'umi-request';
import { message } from 'antd';
// import {
//   BaseApiResponse,
// } from '@/types/soaSocType';
enum Methods {
  POST = 'POST',
  GET = 'GET',
  DELETE = 'DELETE',
  PUT = 'PUT',
}
// 导出能力模板
export const downloadAbilityFile = async () => {
  const data: ArrayBuffer = await getDownloadAbilityFile()
  downloadArrayBufferFile(data, '能力模板')
}

export async function getDownloadAbilityFile() {
  return requestBuffer<ArrayBuffer>(`/api/ms-soa-skill/v1/admin/skill/exportExcelTemplate`, {
    method: Methods.GET,
  });
}

// 导出服务模板
export const downloadServiceFile = async () => {
  const data: ArrayBuffer = await getDownloadServiceFile()
  downloadArrayBufferFile(data, '服务模板')
}

export async function getDownloadServiceFile() {
  return requestBuffer<ArrayBuffer>(`/api/ms-soa-service/v1/admin/carmodel/soc/exportExcelTemplate`, {
    method: Methods.GET,
  });
}
// 下二进制文件 响应content-type需在 downloadContentType内
export const downloadBlobFileByURL = async (url = '', obj: RequestOptionsInit, name = 'file', type='excel') => {
  const data: ArrayBuffer = await requestBuffer<ArrayBuffer>(url, obj);
  downloadArrayBufferFile(data, name, type);
};
export const downloadByFetch = (url = '', obj: RequestOptionsInit, name = 'file') => {
  const str = `${window.g.url}${url}`;
  const newOptions = {
    method: obj.method,
    body: JSON.stringify(obj.data ?? {}),
  };
  const md5Sign = encryptSign(str, obj)
  newOptions.headers = {
    OptAuthorization: getToken(),
    'content-type': 'application/json;charset=UTF-8',
    'accept': 'application/json',
    'shaSign': md5Sign
  };
  fingerprintFetch(str, newOptions)
    .then(response => {
      if (response.status === 200) {
        return response.blob();
      } else {
        throw response;
      }
    })
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${name}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    })
    .catch(() => message.error('导出失败，请稍后在试!'));
};